package com.ruicar.afs.cloud.afscase.archive.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.archive.dto.ArchiveApiDto;
import com.ruicar.afs.cloud.afscase.archive.service.ArchiveApiService;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelQuotaInfo;
import com.ruicar.afs.cloud.afscase.channel.feign.ChannelFeignService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelQuotaInfoService;
import com.ruicar.afs.cloud.afscase.channel.utils.CaseConfig;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.loanapprove.entity.CasePriorityRecord;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CasePriorityChangeService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.CasePriorityRecordService;
import com.ruicar.afs.cloud.archive.dto.DealerDto;
import com.ruicar.afs.cloud.archive.feign.ArchiveApiFeign;
import com.ruicar.afs.cloud.archive.result.ArchivedResultDto;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;

import static com.ruicar.afs.cloud.afscase.channel.common.Constants.QUOTA_OCCUPATION;

/**
 * @Description:
 * @Author: fangchenliang
 * @Date: 2020/8/23 16:43
 */
@Service
@AllArgsConstructor
@Slf4j
@Data
public class ArchiveApiServiceImpl implements ArchiveApiService {

    private CaseContractInfoService caseContractInfoService;

    private ChannelQuotaInfoService channelQuotaInfoService;

    private CaseBaseInfoService caseBaseInfoService;

    private ChannelBaseInfoService channelBaseInfoService;

    private CaseChannelInfoService caseChannelInfoService;

    private ApplyCostDetailsService applyCostDetailsService;

    private CaseConfig caseConfig;

    private ChannelFeignService channelFeignService;

    private ArchiveApiFeign archiveApiFeign;

    private CasePriorityRecordService casePriorityRecordService;

    private CasePriorityChangeService casePriorityChangeService;

    public JSONObject releaseQuota(ArchiveApiDto dto) {
        String contractId = dto.getContractId();
        String contractNo = dto.getContractNo();
        JSONObject jsonObject = new JSONObject();
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery()
                .eq(CaseContractInfo::getContractNo, contractNo)
        );
        if (StringUtils.isNotBlank(contractId) && ObjectUtils.isEmpty(caseContractInfo)) {
            caseContractInfo = caseContractInfoService.getById(Long.valueOf(contractId));
            log.info("======{}额度释放开始=====", contractId);
        }else {
            log.info("======{}额度释放开始=====", contractNo);
        }
        //重复调用返回成功
        if(caseContractInfo != null && QuotaStatusEnum.release.equals(caseContractInfo.getQuotaStatus())){
            jsonObject.put("success",1);
            jsonObject.put("msg","成功");
            log.info("======此合同额度已释放过,重复调用额度释放接口,返回成功标识=====");
            return jsonObject;
        }
        if (!ObjectUtils.isEmpty(caseContractInfo)) {
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>lambdaQuery().eq(CaseBaseInfo::getApplyNo, caseContractInfo.getApplyNo()));
            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda().eq(CaseChannelInfo::getApplyNo, caseContractInfo.getApplyNo()));
            ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
            String quotaType = transLoanMode(caseContractInfo.getLendingMode());
            ChannelQuotaInfo channelQuotaInfo = channelQuotaInfoService.getOne(Wrappers.<ChannelQuotaInfo>query().lambda()
                    .eq(ChannelQuotaInfo::getChannelId, channelBaseInfo.getId())
                    .eq(ChannelQuotaInfo::getBusinessType, caseBaseInfo.getBusinessType())
                    .eq(ChannelQuotaInfo::getQuotaType, quotaType));
            if (!ObjectUtils.isEmpty(channelQuotaInfo)) {
                List<FinCostDetails> costDetailsList = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, caseContractInfo.getApplyNo()));
                BigDecimal amounts = costDetailsList.stream().map(cost -> cost.getLoanAmt())
                        .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(2, BigDecimal.ROUND_HALF_UP);
                /**剩余额度*/
                BigDecimal surplusQuota = channelQuotaInfo.getSurplusQuota() == null ? BigDecimal.ZERO : channelQuotaInfo.getSurplusQuota();
                /**占有额度*/
                BigDecimal OccupiedQuot = channelQuotaInfo.getOccupiedQuota() == null ? BigDecimal.ZERO : channelQuotaInfo.getOccupiedQuota();
                channelQuotaInfo.setOccupiedQuota(OccupiedQuot.subtract(amounts).setScale(2, BigDecimal.ROUND_HALF_UP));
                channelQuotaInfo.setSurplusQuota(surplusQuota.add(amounts).setScale(2, BigDecimal.ROUND_HALF_UP));
                channelQuotaInfoService.updateById(channelQuotaInfo);
                //同步渠道服务,更新额度信息
                List<ChannelQuotaInfo> totalChannelQuotaInfoList = new ArrayList<>();
                totalChannelQuotaInfoList.add(channelQuotaInfo);
                Map<String, String> headers = new HashMap<>();
                headers.put("clientId", caseConfig.getChannelClientId());
                headers.put("clientSecret", caseConfig.getChannelClientSecret());
                channelFeignService.updateChannelQuota(totalChannelQuotaInfoList, headers);
                //合同表额度状态字段改成释放
                caseContractInfo.setQuotaStatus(QuotaStatusEnum.release);
                caseContractInfoService.updateById(caseContractInfo);
                log.info("合同额度释放成功", caseContractInfo.getContractNo());
                jsonObject.put("success",1);
                jsonObject.put("msg","成功");
                return jsonObject;
            } else {
                jsonObject.put("success",0);
                jsonObject.put("code","0");
                jsonObject.put("msg","失败");
                return jsonObject;
            }
        } else {
            jsonObject.put("success",0);
            jsonObject.put("code","0");
            jsonObject.put("msg","失败");
            log.info("======{}此合同号查不到合同信息,额度释放失败=====", contractNo);
            return jsonObject;
        }
    }

    public JSONObject removeOverdue(String dataId) {
        JSONObject jsonObject = new JSONObject();
        log.info("======{}合作商超期解除开始=====", dataId);
        ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelCode, dataId));
        if (ObjectUtils.isEmpty(channelBaseInfo)) {
            channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelId, dataId));
        }
        if (!ObjectUtils.isEmpty(channelBaseInfo)) {
            channelBaseInfo.setIsOverdue(WhetherEnum.NO.getCode());
            channelBaseInfoService.updateById(channelBaseInfo);
                    List<CaseContractInfo> caseContractInfos = caseContractInfoService.getOverdueContractByChannel(channelBaseInfo.getChannelCode());
                    caseContractInfos.forEach(contract->{
                        List<CasePriorityRecord> records=casePriorityRecordService.list(Wrappers.<CasePriorityRecord>lambdaQuery()
                                .eq(CasePriorityRecord::getContractNo,contract.getContractNo()).orderByDesc(CasePriorityRecord::getCreateTime));
                        String priority="5";//默认优先级5
                        if(!CollectionUtils.isEmpty(records)&&records.size()>1) {
                            //如果有历史优先级，恢复之前的优先级
                            priority=records.get(1).getPriority();
                        }
                        contract.setIsOverdue(WhetherEnum.NO.getCode());
                        contract.setPriority(casePriorityChangeService.priorityChange(contract));
                        caseContractInfoService.updateById(contract);
//                        CasePriorityRecord casePriorityRecord = new CasePriorityRecord();
//                        casePriorityRecord.setApplyNo(contract.getApplyNo());
//                        casePriorityRecord.setContractNo(contract.getContractNo());
//                        casePriorityRecord.setPriority(priority);
//                        casePriorityRecord.setReason(PriorityReasonEnum.REMOVE_OVERDUE.getCode());
//                        casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//                        casePriorityRecordService.save(casePriorityRecord);
                    });

            jsonObject.put("code","1");
            jsonObject.put("msg","成功");
            log.info("======{}合作商超期解除结束=====", dataId);
            return jsonObject;
        } else {
            jsonObject.put("code","0");
            jsonObject.put("msg","失败");
            log.info("======{}合作商超期解除结束=====", dataId);
            return jsonObject;
        }
    }

    private String transLoanMode(String lendingMode) {
        if (!ObjectUtils.isEmpty(lendingMode)) {
            if (lendingMode.equals(AfsEnumUtil.key(LoanModelEnum.sign))) {
                /**渠道额度表的额度类型：1，表示签约放款；2，表示抵押签放款*/
                return QuotaTypeEnum.sign.getCode();
            } else if (lendingMode.equals(AfsEnumUtil.key(LoanModelEnum.beforeMortgage))) {
                return QuotaTypeEnum.beforeMortgage.getCode();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    public Boolean setOverdue(String contractNo){
        CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaQuery().eq(CaseContractInfo::getContractNo, contractNo));
        CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda().eq(CaseChannelInfo::getApplyNo, caseContractInfo.getApplyNo()));
        ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
        DealerDto dealerDto =new DealerDto();
        dealerDto.setSigndealerId(channelBaseInfo.getId().toString());
        ArchivedResultDto result = archiveApiFeign.getSingleDealer(dealerDto);
        if(result.getSuccess()==0){
            log.error("经销商{}获取超期信息失败！",channelBaseInfo.getChannelFullName());
            return false;
        }else if(result.getSuccess()==1){
            Map<String,Integer> map=JSONObject.parseObject(result.getData().toString(),Map.class);
            Iterator<Map.Entry<String,Integer>> iterator=map.entrySet().iterator();
            if(iterator.next().getValue()==1){
                caseContractInfo.setIsOverdue(WhetherEnum.YES.getCode());
//                int priority=Integer.valueOf(caseContractInfo.getPriority());
//                if(priority>3){
//                    caseContractInfo.setPriority("3");
//                }
                caseContractInfo.setPriority(casePriorityChangeService.priorityChange(caseContractInfo));
                caseContractInfoService.updateById(caseContractInfo);
//                CasePriorityRecord casePriorityRecord=new CasePriorityRecord();
//                casePriorityRecord.setApplyNo(caseContractInfo.getApplyNo());
//                casePriorityRecord.setContractNo(caseContractInfo.getContractNo());
//                casePriorityRecord.setPriority("3");
//                casePriorityRecord.setReason(PriorityReasonEnum.OVERDUE.getCode());
//                casePriorityRecord.setBusiNode(AfsEnumUtil.key(StepSceneEnum.LOAN));
//                casePriorityRecordService.save(casePriorityRecord);
                if(!WhetherEnum.YES.getCode().equals(channelBaseInfo.getIsOverdue())){
                    channelBaseInfo.setIsOverdue(WhetherEnum.YES.getCode());
                    channelBaseInfoService.updateById(channelBaseInfo);
                }
                log.info("{}经销商{}超期记录成功",channelBaseInfo.getChannelFullName(),contractNo);
            }
            return true;
        }else {
            return false;
        }
    }
}
